package rocky.freemanagementsystemserver.bean

import org.apache.commons.lang3.StringUtils
import org.apache.shiro.authc.AuthenticationInfo
import org.apache.shiro.authc.AuthenticationToken
import org.apache.shiro.authc.SimpleAuthenticationInfo
import org.apache.shiro.authz.AuthorizationInfo
import org.apache.shiro.authz.SimpleAuthorizationInfo
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.springframework.beans.factory.annotation.Autowired
import rocky.freemanagementsystemserver.Entity.User
import rocky.freemanagementsystemserver.service.UserService


open class CustomRealm: AuthorizingRealm() {

    @Autowired
    lateinit var userService: UserService;

    override fun doGetAuthorizationInfo(principalCollection: PrincipalCollection): AuthorizationInfo {
        //获取登录用户名
        //获取登录用户名
        val name = principalCollection.primaryPrincipal as String
        //查询用户名称
        //查询用户名称
        val user: User = userService.getUserByName(name)
        //添加角色和权限
        //添加角色和权限
        val simpleAuthorizationInfo = SimpleAuthorizationInfo()
        for (role in user.roles!!) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.name)
            //添加权限
            for (permissions in role.permissions!!) {
                simpleAuthorizationInfo.addStringPermission(permissions.name)
            }
        }
        return simpleAuthorizationInfo
    }

    /**
     * 这里可以注入userService,为了方便演示，我就写死了帐号了密码
     * private UserService userService;
     * <p>
     * 获取即将需要认证的信息
     */
    override fun doGetAuthenticationInfo(authenticationToken:AuthenticationToken): AuthenticationInfo? {
        if (authenticationToken.principal ==null || StringUtils.isNoneEmpty(authenticationToken.principal as String)) {
            return null
        }
        //获取用户信息
        //获取用户信息
        val name = authenticationToken.principal.toString()
        val user: User = userService.getUserByName(name)
        return if (user == null) {
            //这里返回后会报出对应异常
            null
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo(name, user.password, getName())
        }
    }

}